package lib

import (
	"regexp"
    "net/http"
)

type handleHttpFunction func(http.ResponseWriter, *http.Request)

func InitRoute(w http.ResponseWriter, r *http.Request){
    
    //路由规则
    routes := map[string]handleHttpFunction{
        `^/$`: handleIndex,
        `^/static/`: handleStatic,
        `^/childrenUi$`: childrenUi,
        `^/analy$`: analy,
        `^/childrenMessage$`: getChildrenMessage,
        `^/sign$`: sign,
        `^/childrenSignUi$`: childrenSignUi,
        `^/admin$`: admin,
        `^/admin/login$`: adminLogin,
        `^/admin/ui$`: adminUi,
        `^/admin/sign/edit$`: adminSignEdit,
        `^/admin/sign/doEdit$`: adminSignDoEdit,
        `^/admin/sign/getAll$`: getAllSignTables,
        `^/admin/sign/delete$`: adminDeleteSignTable,
        `^/admin/sign/buildCode$`: adminBuildCode,
        `^/admin/account$`: adminAccount,
        `^/admin/account/doEdit$`: adminAccountDoEdit,
        `^/admin/account/all$`: adminAllChildren,
        `^/admin/account/delete$`: adminRemoveChildrenData,
    }
    
    //防止越权操作
     if r.URL.Path != "/admin" && r.URL.Path != "/admin/login" && len(regexp.MustCompile(`^/admin/`).FindAllString(r.URL.Path, -1)) != 0{
        cookie, err := r.Cookie(ADMIN_TOKEN_KEY)
        if err != nil || cookie.Value != ADMIN_TOKEN{
            w.Header().Set("Location", "/admin")
            w.WriteHeader(302)
        }
    }
    
    notFoundSign := true
    for key, value := range routes{
        
        if len(regexp.MustCompile(key).FindAllString(r.URL.Path, -1)) != 0{
            value(w, r)
            notFoundSign = false
            break
        }
        
    }
    
    //404提示页面
    if notFoundSign{
        w.WriteHeader(404)
        w.Write([]byte("not found!"))
    }
    
}